package com.xinzhi.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/{userId}")
public class WebSocketHandler {
    private static int onLine = 0;
    private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
    private Session session;
    private String userId = "";

    public WebSocketHandler() {
        log.info("WebSocketHandler initialized");
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId = userId;
        this.session = session;

        if (sessions.containsKey(userId)){
            sessions.remove(userId);
            sessions.put(userId,session);
        }else {
            sessions.put(userId,session);
            onLine ++;
        }
        log.info("用户登录：" + userId + "\t" + "当前连接人数：" + onLine);
        try {
            sendSystemMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }
    @OnMessage(maxMessageSize = 500000)
    public void onMessage(Session session, String message) {
        log.info("收到消息：{}", message);
        try {
            JSONObject json = JSON.parseObject(message);
            String type = json.getString("type");
            String content = json.getString("content");
            switch (MessageType.valueOf(type)) {
                case TEXT:
                    handleTextMessage(content);
                    break;
                case IMAGE:
                    handleImageMessage(session, content);
                    break;
                default:
                    log.error("未知的消息类型");
                    break;
            }
        } catch (JSONException | IllegalArgumentException e) {
            log.error("消息格式错误: {}", e.getMessage());
        }
    }

    private void handleTextMessage(String content) {
        // 处理文本消息
        log.info("文本消息：{}", content);
        // 这里可以添加发送文本消息的逻辑
    }

    private void handleImageMessage(Session session, String base64Image) {
        // 处理图片消息
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        String filePath = "D:/file/" + UUID.randomUUID() + ".png";
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(imageBytes);
            log.info("图片已保存，文件路径：{}", filePath);
            // 这里可以添加发送图片消息的逻辑
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @OnError
    public void onError(Session session,Throwable error){
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    @OnClose
    public void onClose(Session session){
        if (sessions.containsKey(userId)){
            sessions.remove(userId);
            onLine --;
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + onLine);
    }

    public void sendSystemMessage(String msg) throws IOException {
        this.session.getBasicRemote().sendText(msg);
    }
}
